import React, { useEffect, useState } from "react";
import { Button, Space, Modal, Input, message } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import LuckyExcel from "luckyexcel";
import { exportExcel } from "../../utils/export";
import "./index.css";

export default () => {
	const [options, setOptions] = useState({
		container: "luckysheet",
		title: "exceledit", //表 头名
		lang: "zh", //中文
		showtoolbar: true, //是否显示工具栏
		showinfobar: false, //是否显示顶部信息栏
		showsheetbar: true, //是否显示底部sheet按钮
		myFolderUrl: "/", //作用：左上角<返回按钮的链接
		row: 30, //行数
		column: 15, //列数
	});

	useEffect(() => {
		luckysheet.create(options);
	}, [options]);

	// 本地导入文件
	function uploadExcel(evt) {
		const files = evt.target.files;
		if (files == null || files.length == 0) {
			alert("没有文件等待导入");
			return;
		}
		let name = files[0].name;
		let suffixArr = name.split("."),
			suffix = suffixArr[suffixArr.length - 1];
		if (suffix != "xlsx") {
			alert("目前只支持导入xlsx文件");
			return;
		}
		LuckyExcel.transformExcelToLucky(files[0], (exportJson, luckysheetfile) => {
			if (exportJson.sheets == null || exportJson.sheets.length == 0) {
				alert("无法读取excel文件的内容，目前不支持xls文件!");
				return;
			}
			window.luckysheet.destroy();
			// 更新数据
			options.data = exportJson.sheets;
			setOptions(options);
			window.luckysheet.create(options);
		});
	}

	const [isModalVisible, setIsModalVisible] = useState(false);
	const [fileName, setFileName] = useState("");

	// 打开弹窗
	function showModal() {
		setIsModalVisible(true);
	}

	// 保存到本地
	const handleOk = () => {
		console.log(fileName);
		if (fileName.trim() !== "") {
			exportExcel(luckysheet.getAllSheets(), fileName);
			setIsModalVisible(false);
		} else {
			message.error("你还没有输入文件名!");
		}
	};

	const handleCancel = () => {
		setIsModalVisible(false);
	};

	return (
		<>
			<div className="excel-main">
				<Space>
					<Button className="fileinput-button">
						<UploadOutlined />
						导入本地xlsx文件
						<input type="file" onChange={(e) => uploadExcel(e)} />
					</Button>
					<Button type="primary" onClick={() => showModal()}>
						导出xlsx文件
					</Button>
				</Space>
				<div id="luckysheet"></div>
			</div>

			<Modal
				title="导出excel文件"
				visible={isModalVisible}
				onOk={handleOk}
				onCancel={handleCancel}
				okText="确认"
				cancelText="取消"
			>
				<Input
					placeholder="输入文件名"
					onChange={(e) => {
						setFileName(e.target.value);
					}}
				/>
			</Modal>
		</>
	);
};
